import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'

export const useLiquidationStore = defineStore('liquidation', () => {
  // 状态
  const coins = ref([])
  const currentCoin = ref(null)
  const loading = ref(false)
  const error = ref(null)
  const searchQuery = ref('')
  const selectedTimeWindow = ref('5m')
  const autoRefresh = ref(true)
  const refreshInterval = ref(null)
  
  // 时间窗口选项
  const timeWindows = ref([
    { key: '1m', label: '1分钟', seconds: 60 },
    { key: '3m', label: '3分钟', seconds: 180 },
    { key: '5m', label: '5分钟', seconds: 300 },
    { key: '10m', label: '10分钟', seconds: 600 },
    { key: '15m', label: '15分钟', seconds: 900 }
  ])
  
  // 计算属性
  const filteredCoins = computed(() => {
    if (!searchQuery.value) {
      return coins.value
    }
    
    const query = searchQuery.value.toLowerCase()
    return coins.value.filter(coin => 
      coin.coin.toLowerCase().includes(query)
    )
  })
  
  const topLiquidationCoins = computed(() => {
    return coins.value
      .filter(coin => coin.timeWindows[selectedTimeWindow.value])
      .sort((a, b) => {
        const aAmount = a.timeWindows[selectedTimeWindow.value].total.amount
        const bAmount = b.timeWindows[selectedTimeWindow.value].total.amount
        return bAmount - aAmount
      })
      .slice(0, 20)
  })
  
  const totalLiquidation = computed(() => {
    const total = {
      long_amount: 0,
      short_amount: 0,
      total_amount: 0,
      long_volume: 0,
      short_volume: 0,
      total_volume: 0,
      long_count: 0,
      short_count: 0,
      total_count: 0
    }
    
    coins.value.forEach(coin => {
      const windowData = coin.timeWindows[selectedTimeWindow.value]
      if (windowData) {
        total.long_amount += windowData.long.amount
        total.short_amount += windowData.short.amount
        total.total_amount += windowData.total.amount
        total.long_volume += windowData.long.volume
        total.short_volume += windowData.short.volume
        total.total_volume += windowData.total.volume
        total.long_count += windowData.long.count
        total.short_count += windowData.short.count
        total.total_count += windowData.total.count
      }
    })
    
    return total
  })
  
  // 方法
  const getAllCoins = async (limit = 100) => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.getAllCoins(limit, selectedTimeWindow.value)
      // API直接返回数组，不是包装在data字段中
      coins.value = response.data || []
      
      return coins.value
    } catch (err) {
      error.value = err.message || '获取币种数据失败'
      console.error('获取币种数据失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  const getCoinStats = async (coinSymbol) => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.getCoinStats(coinSymbol)
      currentCoin.value = response.data
      
      return response.data
    } catch (err) {
      error.value = err.message || '获取币种统计失败'
      console.error('获取币种统计失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  const getTopCoins = async (limit = 50) => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.getTopCoins(limit, selectedTimeWindow.value)
      // API直接返回数组
      coins.value = response.data || []
      
      return coins.value
    } catch (err) {
      error.value = err.message || '获取热门币种失败'
      console.error('获取热门币种失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  const searchCoins = async (query, limit = 20) => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.searchCoins(query, limit)
      return response.data
    } catch (err) {
      error.value = err.message || '搜索币种失败'
      console.error('搜索币种失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  const setTimeWindow = (window) => {
    selectedTimeWindow.value = window
    // 切换时间窗口后重新获取数据
    if (coins.value.length > 0) {
      getAllCoins()
    }
  }
  
  const startAutoRefresh = (interval = 5000) => {
    if (refreshInterval.value) {
      clearInterval(refreshInterval.value)
    }
    
    if (autoRefresh.value) {
      refreshInterval.value = setInterval(() => {
        getAllCoins()
      }, interval)
    }
  }
  
  const stopAutoRefresh = () => {
    if (refreshInterval.value) {
      clearInterval(refreshInterval.value)
      refreshInterval.value = null
    }
  }
  
  const toggleAutoRefresh = () => {
    autoRefresh.value = !autoRefresh.value
    
    if (autoRefresh.value) {
      startAutoRefresh()
    } else {
      stopAutoRefresh()
    }
  }
  
  const clearError = () => {
    error.value = null
  }
  
  const reset = () => {
    coins.value = []
    currentCoin.value = null
    loading.value = false
    error.value = null
    searchQuery.value = ''
    stopAutoRefresh()
  }
  
  const updateCoinData = (newCoinData) => {
    const index = coins.value.findIndex(coin => coin.coin === newCoinData.coin)
    if (index !== -1) {
      coins.value[index] = newCoinData
    } else {
      coins.value.push(newCoinData)
    }
  }
  
  return {
    // 状态
    coins,
    currentCoin,
    loading,
    error,
    searchQuery,
    selectedTimeWindow,
    autoRefresh,
    timeWindows,
    
    // 计算属性
    filteredCoins,
    topLiquidationCoins,
    totalLiquidation,
    
    // 方法
    getAllCoins,
    getCoinStats,
    getTopCoins,
    searchCoins,
    setTimeWindow,
    startAutoRefresh,
    stopAutoRefresh,
    toggleAutoRefresh,
    clearError,
    reset,
    updateCoinData
  }
})